package com.jindu.producer.finance.controller;

import com.jindu.kernel.page.AlphaPage;
import com.jindu.kernel.result.JsonResult;
import com.jindu.kernel.utils.AlphaBeanUtils;
import com.jindu.kernel.utils.DateUtils;
import com.jindu.kernel.utils.IdGenerator;
import com.jindu.producer.finance.api.UserInterface;
import com.jindu.producer.finance.jpa.ExperJpa;
import com.jindu.producer.finance.model.CContentEntity;
import com.jindu.producer.finance.model.FExperEntity;
import com.jindu.producer.finance.model.SUsersEntity;
import com.jindu.producer.finance.shiro.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jarvis
 * @date 2018/1/28
 */
@Api(description = "体验用户管理", tags = "ExperController", basePath = "/exper")
@RestController
@RequestMapping(value = "/exper",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ExperController {

    @Autowired
    ExperJpa experJpa;


    @Autowired
    UserInterface userInterface;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据ID，查询体验用户的信息", notes = "返回单个体验用户的信息")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public JsonResult<FExperEntity> get(@RequestParam String id){
        return JsonResult.getSuccessResult(experJpa.findById(id));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据ID，查询体验用户的列表信息", notes = "返回单个体验用户的列表信息")
    @RequestMapping(value = "getByProductId",method = RequestMethod.GET)
    public JsonResult<AlphaPage<FExperEntity>> getByProductId(@RequestParam(value = "pageNo",defaultValue = "0") Integer pageNo,
                                                         @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                                         @RequestParam(value = "status",required = false) Integer status,
                                                         @RequestParam String productId){

        Specification querySpecifi = (Specification<FExperEntity>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(status != null){
                predicates.add(criteriaBuilder.equal(root.get("status"),status));
            }
            if(productId != null){
                predicates.add(criteriaBuilder.equal(root.get("productId"),productId));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");

        Page<FExperEntity> entities=experJpa.findAll(querySpecifi,new PageRequest(pageNo, pageSize,sort));

        return new AlphaPage<>(entities).toJsonResult();
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "保存体验用户的信息", notes = "保存体验用户的信息")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public JsonResult<FExperEntity> save(@RequestBody FExperEntity experEntity){

        FExperEntity fExperEntity=experJpa.findById(experEntity.getId());

        if(fExperEntity == null){
            experEntity.setId(IdGenerator.uuid());
            experEntity.setCreateTime(new Timestamp(DateUtils.getCurrentTime()));
            experEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            return JsonResult.getSuccessResult(experJpa.saveAndFlush(experEntity));
        }else {
            experEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            BeanUtils.copyProperties(experEntity,fExperEntity, AlphaBeanUtils.getNullPropertyNames(experEntity));
            return JsonResult.getSuccessResult(experJpa.saveAndFlush(fExperEntity));
        }
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "保存申请体验用户的信息", notes = "保存申请体验用户的信息")
    @RequestMapping(value = "saveByUserId", method = RequestMethod.POST)
    public JsonResult<FExperEntity> saveByUserId(ServletRequest request,
                                                 @RequestParam String productId){

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");

        if(authorization!=null) {

            String userId = JwtUtils.getUserId(authorization);
            SUsersEntity usersEntity=userInterface.get(userId).getContent();

            List<FExperEntity> ex=experJpa.findByUserIdAndProductId(userId,productId);

            if(ex.size()==0){
                FExperEntity fExperEntity=new FExperEntity();

                fExperEntity.setId(IdGenerator.uuid());
                fExperEntity.setUserId(userId);
                fExperEntity.setAvatar(usersEntity.getImageUrl());
                fExperEntity.setNickName(usersEntity.getNickname());
                fExperEntity.setProductId(productId);
                fExperEntity.setStatus(1);
                fExperEntity.setCreateId(userId);
                fExperEntity.setModifyId(userId);
                fExperEntity.setCreateTime(new Timestamp(DateUtils.getCurrentTime()));
                fExperEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));

                return JsonResult.getSuccessResult(experJpa.saveAndFlush(fExperEntity));
            }
            else {
                return JsonResult.getFailureByRepeatData();
            }
        }else {
            return JsonResult.getFailureByNoAuthorization();
        }
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "删除体验用户的信息", notes = "根据体验用户的ID,删除数据")
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public JsonResult<Integer> delete(@RequestBody String id){
        return JsonResult.getSuccessResult(experJpa.deleteById(id));
    }









}
